public class 去除重复字母 {
    public static int MAXN = 10001;
    public static char[] stack = new char[MAXN];
    public static boolean[] vis = new boolean[26];
    public static int[] hash = new int[26];
    public static int r;
    public String removeDuplicateLetters(String ss) {
        char[] s = ss.toCharArray();
        int n = s.length;
        r = 0;
        for (char ch : s) {
            hash[ch - 'a']++;
        }
        for (char cur : s) {
            if (!vis[cur - 'a']) {
                while (r > 0 && stack[r - 1] > cur && hash[cur - 'a'] > 0) {
                    vis[stack[r - 1] - 'a'] = false;
                    r--;
                }
                stack[r++] = cur;
                vis[cur - 'a'] = true;
            }
            hash[cur - 'a']--;
        }
        return String.valueOf(stack,0,r);
    }
}
